var express = require('express');
var createError = require('http-errors');
var musr = require('./users');
var mapi = require('./api');
var router = express.Router();

router.post('/logout', function (req, res, next) {
    var cur_user = musr.getUser(req);
    if (cur_user) {
        musr.logout(cur_user);
        req.session.destroy();
        res.send({ "success": true, "err": "" });
    } else {
        res.send({ "success": false, "err": "not logined" });
    }
});

router.post('/login', function (req, res, next) {
    if (musr.isLogined(req)) {
        res.send({ "success": false, "err": "already logined" });
    } else {
        var ret = musr.login(req.body.username, req.body.password);
        if (ret === -1) {
            req.session.destroy();
            res.send({ "success": false, "err": "bad user or pwd" });
        } else {
            req.session.user = req.body.username;
            req.session.timestamp = ret;
            res.send({ "success": true, "err": "" });
        }
    }
});

router.post('/chpwd', function (req, res, next) {
    if (!musr.isLogined(req)) {
        res.send({ "success": false, "err": "not logined" });
    } else {
        res.send({ "success": musr.chpwd(req.session.user, req.body.old, req.body.new), "err": "" });
    }
});

router.post('/setpwd', function (req, res, next) {
    if (!musr.isAdmin(req)) {
        res.send({ "success": false, "err": "not logined" });
    } else {
        res.send({ "success": musr.setpwd(req.body.usr, req.body.pwd), "err": "" });
    }
});

router.post('/register', function (req, res, next) {
    if (!musr.isAdmin(req)) {
        res.send({ "success": false, "err": "not admin" });
    } else {
        res.send({ "success": musr.register(req.body.usr, req.body.pwd), "err": "" });
    }
});

router.post('/unreg', function (req, res, next) {
    if (!musr.isAdmin(req)) {
        res.send({ "success": false, "err": "not admin" });
    } else {
        res.send({ "success": musr.unreg(req.body.usr), "err": "" });
    }
});

module.exports = router;